package cn.wx.scholar.tool.jwt;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.wx.common.persistence.exception.MyException;
import cn.wx.common.persistence.web.ResponseCode;

import java.util.*;

public class JwtUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(JwtUtil.class);
	public static final long EXPIRATION_TIME = 2592000_000L; // 30days
	
	//public static final long EXPIRATION_TIME = 10000;
	
	public static final String SECRET = "mqr9fTHee5awUEA0";//加密参数
	public static final String TOKEN_PREFIX = "Bearer";
	public static final String HEADER_STRING = "Authorization";
	public static final String USER_ID = "userId";

	public static String generateToken(Long userId) {
		HashMap<String, Object> map = new HashMap<>();
		try {
			map.put(USER_ID, EncryptUtil.encrypt(userId.toString()));
		} catch (Exception e) {
			logger.warn("Encryption failed. " + e.getMessage());
			throw new MyException(ResponseCode.JWT_CHECK_ERROR);
		}
		String jwt = Jwts.builder()
				.setClaims(map)
				.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
				.signWith(SignatureAlgorithm.HS512, SECRET)
				.compact();
		return jwt;
	}
	
	public static Long validateToken(String token) {
		
		if (token == null) {
			logger.info("Missing token");
			throw new MyException(ResponseCode.JWT_CHECK_ERROR);
		}
		
		try {
			String tokenBody=token.replace(TOKEN_PREFIX, "");
			Map<String, Object> body = Jwts.parser()
					.setSigningKey(SECRET)
					.parseClaimsJws(tokenBody)
					.getBody();
			String userId = (String) body.get(USER_ID);
			return Long.parseLong(EncryptUtil.decrypt(userId));
		} catch (Exception e) {
			logger.info("token认证错误" + e.getMessage());
			throw new MyException(ResponseCode.JWT_CHECK_ERROR);
		}
		
	}

}